Templates
If you have any other templates you want added here, then just send them to the TA.
Parsing Arguments
In order to write a script with arguments, some funniness needs to happen in terms of parsing. The short of it is that nobody wants to build a parser, but bash kind-of-sort-of provides one for us to use. You can download this template if you want.
#!/bin/bash
############################################################
# Help #
############################################################
Help()
{
# Display Help
echo "Add description of the script functions here."
echo
echo "Syntax: scriptTemplate [-g|h|v|V]"
echo "options:"
echo "g Print the GPL license notification."
echo "h Print this Help."
echo "v Verbose mode."
echo "V Print software version and exit."
echo
}
############################################################
############################################################
# Main program #
############################################################
############################################################
# Set variables
Name="world"
############################################################
# Process the input options. Add options as needed. #
############################################################
# Get the options
while getopts ":hn:" option; do
case $option in
h) # display Help
Help
exit;;
n) # Enter a name
Name=${OPTARG};;
\?) # Invalid option
echo "Error: Invalid option"
exit;;
esac
done
echo "hello $Name!"
The parser (getopts
) in bash is pretty... simple. Command flags in this case are -h
and -n
, however you can observe some odd quirks:
- Passing
-nBeans
and-n Beans
will both yield the same result - Passing
-h
,-h**
and any other sequence will always print help - Passing
-n Beans -h
will print the help information - Adding a colon behind an option makes it accept an argument, which you can then get through
${OPTARG}
There's a lot of weird stuff, but you know what, there are worse things in the world.
Prettification
You may find the following function useful if you want to make everything you do pretty:
################### PRETTIFICATION ######################
RED="\033[0;91m"
GREEN="\033[0;92m"
YEL="\033[0;93m"
PPL="\033[0;35m"
CLR="\033[0m"
function echoRed() {
echo -e "$RED$1$CLR"
}
function echoGreen() {
echo -e "$GREEN$1$CLR"
}
function echoPurple() {
echo -e "$PPL$1$CLR"
}
function echoYellow() {
echo -e "$YEL$1$CLR"
}
function echoError() {
echo -e "$(echoRed "ERROR: ")$1"
}
function echoWarn() {
echo -e "$(echoYellow "WARNING: ")$1"
}
For a complete list of the terminal colours available when using the ANSI terminal colours, consult this comment with this good graphic and then this site for applications.